﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Yuebon.Car.IServices;
using Yuebon.Car.Models;
using Yuebon.Commons.Helpers;
using Yuebon.Commons.Models;
using Yuebon.Commons.Tree;
using Yuebon.WebApp.Controllers;
using NPinyin;
using Yuebon.Commons.Extensions;
using Yuebon.WebApp.Models;
using System.Reflection;
using Yuebon.Commons.Log;
using Yuebon.Car.Application;

namespace Yuebon.WebApp.Areas.Car.Controllers
{
    [Area("Car")]
    [Route("Car/[controller]/[action]")]
    public class AutoBrandController : BusinessController<AutoBrand, IAutoBrandService>
    {

        public AutoBrandController(IAutoBrandService _iService) : base(_iService)
        {
            iService = _iService;

            AuthorizeKey.InsertKey = "AutoBrand/Add";
            AuthorizeKey.UpdateKey = "AutoBrand/Edit";
            AuthorizeKey.DeleteKey = "AutoBrand/Delete";
            AuthorizeKey.UpdateEnableKey = "AutoBrand/Enable";
            AuthorizeKey.ListKey = "AutoBrand/List";
            AuthorizeKey.ViewKey = "AutoBrand/View";
        }

        protected override void OnBeforeInsert(AutoBrand info)
        {
            //留给子类对参数对象进行修改
            info.Id = GuidUtils.CreateNo();
            info.CreatorTime = DateTime.Now;
            info.CreatorUserId = CurrentUser.Id;
            info.DeleteMark = false;
            info.LastLetter = Pinyin.GetInitials(info.Title.Substring(0, 1));
            if (info.SortCode == null)
            {
                info.SortCode = 99;
            }

        }

        /// <summary>
        /// 在更新数据前对数据的修改操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override void OnBeforeUpdate(AutoBrand info)
        {
            //留给子类对参数对象进行修改 
            info.LastModifyTime = DateTime.Now;
            info.LastModifyUserId = CurrentUser.Id;
            info.LastLetter = Pinyin.GetInitials(info.Title.Substring(0,1));
            if (info.SortCode == null)
            {
                info.SortCode = 99;
            }
        }
        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <returns>指定对象的集合</returns>
        [HttpGet]
        public override IActionResult FindWithPager()
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.ListKey);
            string keywords = Request.Query["search"].ToString() == null ? "" : Request.Query["search"].ToString();
            string orderByDir = Request.Query["order"].ToString() == null ? "" : Request.Query["order"].ToString();
            string orderFlied = Request.Query["sort"].ToString() == "" ? "Id" : Request.Query["sort"].ToString();
            string where = GetPagerCondition();
            bool order = orderByDir == "asc" ? false : true;
            if (!string.IsNullOrEmpty(keywords))
            {
                where += string.Format(" and (Title like '%{0}%' or SeoTitle like '%{0}%')", keywords);
            }
            PagerInfo pagerInfo = GetPagerInfo();
            List<AutoBrand> list = iService.FindWithPager(where, pagerInfo, orderFlied, order);

            //构造成Json的格式传递
            var result = new
            {
                total = pagerInfo.RecordCount,
                rows = list
            };
            return ToJsonContent(result);
        }


        /// <summary>
        /// 根据条件查询数据库,并返回对象集合
        /// </summary>
        /// <returns>指定对象的集合</returns>
        [HttpGet]
        public IActionResult GetAll()
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            //base.CheckAuthorized(AuthorizeKey.ListKey);
            string keywords = Request.Query["search"].ToString() == null ? "" : Request.Query["search"].ToString();
            string orderByDir = Request.Query["order"].ToString() == null ? "" : Request.Query["order"].ToString();
            string orderFlied = Request.Query["sort"].ToString() == "" ? "SortCode" : Request.Query["sort"].ToString();
            string where = "1=1";
            bool order = orderByDir == "asc" ? false : true;
            if (!string.IsNullOrEmpty(keywords))
            {
                where += string.Format(" and Title like '%{0}%' ", keywords);
            }
            List<AutoBrand> list = iService.GetListWhere(where).OrderBy(t => t.SortCode).ToList();
            var treeList = new List<TreeSelectModel>();
            foreach (AutoBrand item in list)
            {
                TreeSelectModel treeModel = new TreeSelectModel();
                treeModel.id = item.Id;
                treeModel.text = item.Title;
                treeModel.parentId = "";
                treeList.Add(treeModel);
            }
            return ToJsonContent(treeList.TreeSelectJson());
        }

        /// <summary>
        /// 删除多个ID的记录
        /// </summary>
        /// <param name="ids">多个id组合，逗号分开（1,2,3,4,5）</param>
        /// <returns></returns>
        public override IActionResult DeleteByIds(string ids)
        {
            //检查用户是否有权限，否则抛出MyDenyAccessException异常
            CheckAuthorized(AuthorizeKey.DeleteKey);
            CommonResult result = new CommonResult();
            try
            {
                AutoDetailsApp autoDetailsApp = new AutoDetailsApp();
                int isok = autoDetailsApp.GetWhereByBrandid(ids);
                if (isok == 0)
                {
                    if (!string.IsNullOrEmpty(ids))
                    {
                        List<string> idArray = ids.ToDelimitedList<string>(",");
                        foreach (string strId in idArray)
                        {
                            if (!string.IsNullOrEmpty(strId))
                            {
                                bool bl = iService.Delete(strId);
                                if (bl)
                                {
                                    result.ErrCode = ErrCode.successCode;
                                    result.ErrMsg = ErrCode.err0;
                                    result.Success = true;
                                }
                                else
                                {
                                    result.ErrMsg = ErrCode.err43003;
                                    result.ErrCode = "43003";
                                }
                            }
                        }
                    }
                }
                else {
                    result.ErrMsg = ErrCode.err60001;
                    result.ErrCode = "60001";
                }
            }
            catch (Exception ex)
            {
                var type = MethodBase.GetCurrentMethod().DeclaringType;
                Log4NetHelper.WriteError(type, ex);//错误记录
                result.ErrMsg = ex.Message;
            }
            return ToJsonContent(result);
        }
    }
}